package com.example.baidumap_a;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Text;
import com.baidu.mapapi.model.LatLng;
import com.example.baidumap_a.Activity.PayActivity;
import com.example.baidumap_a.entity.Ohuang;
import com.example.baidumap_a.entity.ParkLocation;
import com.example.baidumap_a.entity.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MapActivity extends AppCompatActivity {
    private MapView mapView;
    private BaiduMap baiduMap;
    private LocationClient mLocationClient = null;

    private MapActivity.bdAbstractLocationListener mybdAbstractLocationListener;
    private double currentLat, currentLng;//纬度 经度
    private boolean flag;

    private ArrayList<ParkLocation> listPark;
    private View mark_park;//覆盖物
    private Marker marker;
    private String name;
    private OkHttpClient client= new OkHttpClient();;
    private static final int JSON_OK = 1, JSON_NO = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        Intent intent = getIntent();
        name = intent.getStringExtra("username");
        mapView = findViewById(R.id.map_bmapView);
        mark_park = getLayoutInflater().inflate(R.layout.prak_show, null);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        Ohuang.startGps(this, this);//GPS权限申请和打开
        initBaiduMap();//初始化地图
        mylocation();//显示我的位置+
        initMapClickListener();//地图监听初始化


    }


    private void PostHttpRequest() {
        RequestBody formBody = new FormBody.Builder()
                .build();

        final Request request = new Request.Builder()
                .url("https://d30n971042.imdo.co/park/findAllPark")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                myHandler.sendEmptyMessage(JSON_NO);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                ResponseBody body = response.body();
                if (body != null) {
                    String json = body.string();
                    Gson gson = new Gson();
                    Type type = new TypeToken<ArrayList<ParkLocation>>() {
                    }.getType();
                    listPark = gson.fromJson(json, type);
                    body.close();
                }

                myHandler.sendEmptyMessage(JSON_OK);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case JSON_OK:
                    addOverlay(listPark);
                    break;

                case JSON_NO:
                    Toast.makeText(MapActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    //初始化地图
    private void initBaiduMap() {
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);

        mLocationClient = new LocationClient(getApplicationContext());//声明LocationClient
//        myLocationListener = new MapActivity.MyLocationListener();
        mybdAbstractLocationListener = new bdAbstractLocationListener();
//        mLocationClient.registerLocationListener(myLocationListener);//注册监听函数
        mLocationClient.registerLocationListener(mybdAbstractLocationListener);

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式
        option.setCoorType("gcj02");//返回的定义结果是百度经纬度,默认是gcj02
        option.setScanSpan(10000);//设置发起定位请求间隔为10000ms
        option.setIsNeedAddress(true);//返回结果包含地址信息
        option.setNeedDeviceDirect(true);//返回的定位结果包含手机机头的方向
        mLocationClient.setLocOption(option);

        mLocationClient.start(); //开启地图定位图层
        mLocationClient.requestLocation();//发送请求

    }

    //显示我的位置
    private void mylocation() {
        Toast.makeText(MapActivity.this, "正在定位...", Toast.LENGTH_SHORT).show();
        flag = true;
        baiduMap.clear();
        baiduMap.setMyLocationEnabled(true);
        mLocationClient.requestLocation();//发送定位请求
    }

    //我的位置按钮
    public void map_MyCLick(View view) {
        initBaiduMap();
        mylocation();

    }

    //显示停车场按钮
    public void map_PackCLick(View view) {
        PostHttpRequest();
    }

//    //参数
//    private void setMarkerInfo() {
//        infos = new ArrayList<MarkerInfoUtil>();
//        infos.add(new MarkerInfoUtil(29.82500, 121.570500, "天津站", R.drawable.park_1, "天津站，俗称天津东站，隶属北京铁路局管辖"));
//        infos.add(new MarkerInfoUtil(29.826500, 121.571500, "南开大学", R.drawable.park_1, "正式成立于1919年，是由严修、张伯苓秉承教育救国理念创办的综合性大学。"));
//        infos.add(new MarkerInfoUtil(29.825500, 121.571000, "天津水上公园", R.drawable.park_1, "天津水上公园原称青龙潭，1951年7月1日正式对游客开放，有北方的小西子之称。"));
//    }

    //将停车场添加到图层
//    private void showPark() {
//        List<OverlayOptions> listOverlayOptions = new ArrayList<>();
//        LatLng latLng1 = new LatLng(29.829035, 121.513247);//经纬度
//        LatLng latLng2 = new LatLng(29.809035, 121.513247);//经纬度
//        LatLng latLng3 = new LatLng(29.809035, 121.533247);//经纬度
//        //构建图片描述器
//        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.park_1);
//        //创建一个图层选项
//        OverlayOptions options1 = new MarkerOptions().position(latLng1).icon(bitmapDescriptor);
//        OverlayOptions options2 = new MarkerOptions().position(latLng2).icon(bitmapDescriptor);
//        OverlayOptions options3 = new MarkerOptions().position(latLng3).icon(bitmapDescriptor);
//        listOverlayOptions.add(options1);
//        listOverlayOptions.add(options2);
//        listOverlayOptions.add(options3);
//        //把图层选项添加到地图
//        baiduMap.addOverlays(listOverlayOptions);
//
//    }
    //将停车场添加到图层
    private void addOverlay(ArrayList<ParkLocation> infos2) {
        //清空地图
        baiduMap.clear();
        //创建marker的显示图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.park_1);
        LatLng latLng = null;
        Marker marker;
        OverlayOptions options;
        for (ParkLocation info : infos2) {
            //获取经纬度
            double ParLat = Double.parseDouble(info.getLatitude());
            double ParkLon = Double.parseDouble(info.getLongitude());
            Gps ParkGps = PositionUtil.gps84_To_Gcj02(ParLat, ParkLon);
            latLng = new LatLng(ParkGps.getWgLat(), ParkGps.getWgLon());
            //设置marker
            options = new MarkerOptions()
                    .position(latLng)//设置位置
                    .icon(bitmap); //设置图标样式

            //添加marker
            marker = (Marker) baiduMap.addOverlay(options);
            //使用marker携带info信息，当点击事件的时候可以通过marker获得info信息
            Bundle bundle = new Bundle();
            //info必须实现序列化接口
            bundle.putSerializable("info", info);
            bundle.putDouble("lat",ParkGps.getWgLat());
            bundle.putDouble("lon", ParkGps.getWgLon());
            marker.setExtraInfo(bundle);
        }

    }


    //地图监听
    private void initMapClickListener() {
        //Mark监听
        BaiduMap.OnMarkerClickListener markerClickListener = new BaiduMap.OnMarkerClickListener() {
            /**
             * 地图 Marker 覆盖物点击事件监听函数
             * @param marker 被点击的 marker
             */
            public boolean onMarkerClick(Marker marker) {
                Bundle bundle = marker.getExtraInfo();
                final ParkLocation infoUtil = (ParkLocation) bundle.getSerializable("info");//获取bundle里的数据
                final double Lat=bundle.getDouble("lat",0.0);
                final double Lon=bundle.getDouble("lon",0.0);
                TextView text = mark_park.findViewById(R.id.park_tv_name);
                Button button1 = mark_park.findViewById(R.id.park_btn_detail);
                Button button2 = mark_park.findViewById(R.id.park_btn_navigation);
                Button button3 = mark_park.findViewById(R.id.park_btn_cancel);
                text.setText(infoUtil.getCarName());
                button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MapActivity.this, PayActivity.class);
                        intent.putExtra("username",name);
                        intent.putExtra("id",infoUtil.getCarId());
                        startActivity(intent);//进入车位预订界面
                    }
                });

                button2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startNaviActivty(Lat, Lon);//进入导航界面
                    }
                });
                button3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        baiduMap.hideInfoWindow();//隐藏
                    }
                });
                mark_park.setVisibility(View.VISIBLE);
                LatLng latLng = new LatLng(Lat,Lon);//infowindow位置

                //显示infowindow
                InfoWindow infoWindow = new InfoWindow(mark_park, latLng, -47);
                baiduMap.showInfoWindow(infoWindow);

                return true;
            }
        };


        baiduMap.setOnMarkerClickListener(markerClickListener);
    }

    //开启导航
    private void startNaviActivty(double latitude, double longitude) {
        Gps startGps = PositionUtil.gcj_To_Gps84(currentLat, currentLng);//坐标系转化
        Gps endGps = PositionUtil.gcj_To_Gps84(latitude, longitude);//坐标系转化
        Intent intent = new Intent(MapActivity.this, DemoMainActivity.class);
        intent.putExtra("endLongitude", endGps.getWgLon());
        intent.putExtra("endLatitude", endGps.getWgLat());
        intent.putExtra("startLatitude", startGps.getWgLat());
        intent.putExtra("startLongitude", startGps.getWgLon());
        startActivity(intent);
    }

    public void map_CloseCLick(View view) {
        finish();
    }

    //位置初始化监听
    class bdAbstractLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation != null & flag) {
                flag = false;
                currentLat = bdLocation.getLatitude();
                currentLng = bdLocation.getLongitude();
                MyLocationData.Builder builder = new MyLocationData.Builder();
                builder.latitude(bdLocation.getLatitude());//设置纬度
                builder.longitude(bdLocation.getLongitude());//设置经度
                builder.accuracy(bdLocation.getRadius());//设置精度(半径)
                builder.direction(bdLocation.getDirection());//设置方向
                builder.speed(bdLocation.getSpeed());//设置速度
                MyLocationData locationData = builder.build();
                baiduMap.setMyLocationData(locationData);
                LatLng latLng = new LatLng(currentLat, currentLng);
                baiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.FOLLOWING, true, null));
                //设置我的位置为地图的中心点
                baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngZoom(latLng, 16));

            }
            if (bdLocation != null & !flag) {
                currentLat = bdLocation.getLatitude();
                currentLng = bdLocation.getLongitude();

            }
            System.out.println("纬度：" + currentLat + "经度" + currentLng);
        }
    }


}
